
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
var __spreadArrays = (this && this.__spreadArrays) || function () {
    for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
    for (var r = Array(s), k = 0, i = 0; i < il; i++)
        for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
            r[k] = a[j];
    return r;
};
Object.defineProperty(exports, "__esModule", { value: true });
/**
* @module session-manager
* @author: Hjava
* @description: 会话管理模块
* @since: 2018-07-23 12:57:05
*/
var create_readitem_1 = __webpack_require__(/*! _Eutils/create-readitem */ "./src/extra/utils/create-readitem.ts");
var event_emitter_1 = __webpack_require__(/*! _Eutils/event-emitter */ "./src/extra/utils/event-emitter.ts");
var map_1 = __webpack_require__(/*! _Eutils/map */ "./src/extra/utils/map.ts");
var sessionIdProcessor_1 = __webpack_require__(/*! _Eutils/sessionIdProcessor */ "./src/extra/utils/sessionIdProcessor.ts");
var constant_1 = __webpack_require__(/*! _util/constant */ "./src/core/utils/constant.ts");
var promise_1 = __webpack_require__(/*! _util/promise */ "./src/core/utils/promise.ts");
var userData_1 = __webpack_require__(/*! _util/userData */ "./src/core/utils/userData.ts");
var models_1 = __webpack_require__(/*! ../models */ "./src/extra/models/index.ts");
var config_manager_1 = __webpack_require__(/*! ./config-manager */ "./src/extra/managers/config-manager.ts");
var message_manager_1 = __webpack_require__(/*! ./message-manager */ "./src/extra/managers/message-manager.ts");
var typeChecker_1 = __webpack_require__(/*! _util/typeChecker */ "./src/core/utils/typeChecker.ts");
var analytics_1 = __webpack_require__(/*! _util/analytics */ "./src/core/utils/analytics.ts");
var constant_2 = __webpack_require__(/*! ../../core/utils/constant */ "./src/core/utils/constant.ts");
var log_1 = __webpack_require__(/*! ./../utils/log */ "./src/extra/utils/log.ts");
var message_util_1 = __webpack_require__(/*! _Eutils/message-util */ "./src/extra/utils/message-util.ts");
var constant_3 = __webpack_require__(/*! _util/constant */ "./src/core/utils/constant.ts");
var BIG_TIME = '9223372036854775807'; //Long型最大值,直接复用
var DAO;
if (false) {}
else {
    DAO = __webpack_require__(/*! ../dao */ "./src/extra/dao/index.ts").default;
}
// 已读同步重试时间
var READ_RETRY_TIME = 5 * 1000;
// 默认不获取会话列表,给出提示需要用户手动配置
var TIME_RANGE = 0;
// 获取会话列表请求最大重试次数
var SESSION_LIST_RETRY_MAX_TIMES = 3;
// indexedDB 数据库名称
var DB_SESSION = 'session';
// IM 未读数最大补全时间:1 个月
var IM_EARLIEST_TIME_IN_HISTORY_RANGE = 30 * 24 * 60 * 60 * 1000;
// PUB 未读数最大补全时间:1 个月
var PUB_EARLIEST_TIME_IN_HISTORY_RANGE = 7 * 24 * 60 * 60 * 1000;
var SessionManager = /** @class */ (function () {
    function SessionManager() {
        this._isFirstInit = true;
        this._sessionMap = new map_1.default();
        this._readSendMap = new map_1.default();
        // 由于后端存储默认值设置为 5 天,保持默认值一致,业务方可以自行设置(需要提前周知存储服务)
        this._IMTimeRange = TIME_RANGE;
        this._PubTimeRange = TIME_RANGE;
        // 拉取会话列表最早时间,用于循环拉取会话列表
        this._lastFetchIMSessionListTime = Date.now();
        this._lastFetchPubSessionListTime = Date.now();
        this._imSessionListRetryTime = 0;
        this._pubSessionListRetryTime = 0;
        this._isLoginSuccessSessionListGetFinish = false;
        this._deleteSessionDataMessageCache = [];
        this.mtdx = {};
        this._sessionMap = new map_1.default();
    }
    SessionManager.prototype.init = function (mtdx) {
        var _this = this;
        log_1.default.log('SessionManager::init');
        this.mtdx = mtdx;
        event_emitter_1.default.on(event_emitter_1.EVENT_NAME.AUTH_SUCCESS, function () {
            log_1.default.log('SessionManager::init EVENT_NAME.AUTH_SUCCESS');
            _this._isLoginSuccessSessionListGetFinish = false;
            var initAfterLoginTime = Date.now();
            if (!_this._IMTimeRange) {
                log_1.default.warn('SessionManager::init 没有设置 IM 会话列表获取时间,如果为已知情况请忽略本提示');
            }
            if (!_this._PubTimeRange) {
                log_1.default.warn('SessionManager::init 没有设置 PUB 会话列表获取时间,如果为已知情况请忽略本提示');
            }
            _this._imSessionListRetryTime = 0;
            _this._pubSessionListRetryTime = 0;
            _this.fetchRemoteSessionListAndCountUnreadByHistoryMessages({}).then(function () {
                log_1.default.log('SessionManager::init EVENT_NAME.UNREADS_COUNT_FINISHED');
                _this._isLoginSuccessSessionListGetFinish = true;
                event_emitter_1.default.emit(event_emitter_1.EVENT_NAME.UNREADS_COUNT_FINISHED);
                analytics_1.default.report({
                    nm: 'session_init_success',
                    val: {
                        time: Date.now() - initAfterLoginTime
                    }
                });
            });
        });
        event_emitter_1.default.on(event_emitter_1.EVENT_NAME.LOGOUT, function () {
            log_1.default.log('SessionManager::init EVENT_NAME.LOGOUT');
            _this.clearAllSessionsAndMessages();
        });
        event_emitter_1.default.on(event_emitter_1.EVENT_NAME.MESSAGE, function (_a, shouldUpdateSession) {
            var message = _a.message;
            if (shouldUpdateSession === void 0) { shouldUpdateSession = false; }
            // Log.log('SessionManager::init EVENT_NAME.MESSAGE info:' + message + ' shouldUpdateSession:' + shouldUpdateSession)
            if (shouldUpdateSession) {
                _this.updateSessionByMessageAndSave(message);
            }
        });
        event_emitter_1.default.on(event_emitter_1.EVENT_NAME.UPDATE_MESSAGES, function (_a) {
            // Log.log('SessionManager::init EVENT_NAME.UPDATE_MESSAGES uid:' + uid + ' channelId:' + channelId + ' sid:' + sid + ' fromSource:' + fromSource)
            var uid = _a.uid, channelId = _a.channelId, sid = _a.sid, messages = _a.messages, fromSource = _a.fromSource;
            var existMessages = message_manager_1.default.getMessages(uid, channelId, sid);
            if (existMessages && existMessages.length > 0) {
                var lastMessage = existMessages[existMessages.length - 1];
                var session = _this.getSession(uid, channelId, sid);
                // 只有来自历史的需要主动更新,否则会通过 MESSAGE 事件更新
                if (session && fromSource === constant_1.MESSAGE_SOURCE.HISTORY && (!session.message || (session.message.svrTime < lastMessage.svrTime))) {
                    log_1.default.log('SessionManager::init EVENT_NAME.UPDATE_MESSAGES update session message:' + lastMessage);
                    session.message = lastMessage;
                    _this.saveSessions([session]);
                }
            }
        });
        event_emitter_1.default.on(event_emitter_1.EVENT_NAME.ADD_FAKE_MESSAGE, function (_a) {
            var message = _a.message;
            log_1.default.log('SessionManager::init EVENT_NAME.ADD_FAKE_MESSAGE info:' + message);
            _this.updateSessionByMessageAndSave(message);
        });
        event_emitter_1.default.on(event_emitter_1.EVENT_NAME.DATA_MESSAGE, function (_a) {
            var message = _a.message;
            if (!message) {
                return;
            }
            _this.dealReceiveDataMessage([message]);
        });
        event_emitter_1.default.on(event_emitter_1.EVENT_NAME.DATA_MESSAGE_OFFLINE, function (_a) {
            var messages = _a.messages;
            _this.dealReceiveDataMessage(messages);
        });
        event_emitter_1.default.on(event_emitter_1.EVENT_NAME.UNREADS_COUNT_FINISHED, function (_a) {
            _this.dealReceiveDataMessage(_this._deleteSessionDataMessageCache);
            _this._deleteSessionDataMessageCache = [];
        });
        this.mtdx.on(constant_1.MESSAGE_EVENT.IM_READ, function (res) {
            var parseObject = _this._parseIMRead(res);
            // Log.log('SessionManager::init EVENT_NAME.IM_READ info:' + parseObject)
            _this.updateSessionsByReadsAndSave(parseObject);
        });
        this.mtdx.on(constant_1.MESSAGE_EVENT.PUB_READ, function (res) {
            // Log.log('SessionManager::init EVENT_NAME.PUB_READ info:' + res)
            _this.updateSessionsByReadsAndSave(_this._parsePubRead(res));
        });
        this.mtdx.on(constant_1.MESSAGE_EVENT.IM_READ_ACK, this.handleReadAck.bind(this));
        this.mtdx.on(constant_1.MESSAGE_EVENT.PUB_READ_ACK, this.handleReadAck.bind(this));
    };
    SessionManager.prototype.clearAllSessionsAndMessages = function () {
        this._sessionMap = new map_1.default();
        this._readSendMap = new map_1.default();
        this._lastFetchIMSessionListTime = Date.now();
        this._lastFetchPubSessionListTime = Date.now();
        this._imSessionListRetryTime = 0;
        this._pubSessionListRetryTime = 0;
        message_manager_1.default.clearAllMessages();
    };
    SessionManager.prototype.setInitData = function () {
        log_1.default.warn('setInitData 已废弃,请使用 setInitialTimeRange,具体使用方式见文档: https://km.sankuai.com/page/172625954');
    };
    SessionManager.prototype.setInitialTimeRange = function (_a) {
        var _b = _a.IMTimeRange, IMTimeRange = _b === void 0 ? TIME_RANGE : _b, _c = _a.PubTimeRange, PubTimeRange = _c === void 0 ? TIME_RANGE : _c;
        this._IMTimeRange = IMTimeRange;
        this._PubTimeRange = PubTimeRange;
    };
    SessionManager.prototype.hasLocalSession = function (uid, channelId, sid) {
        if (uid === void 0) { uid = ''; }
        if (channelId === void 0) { channelId = userData_1.default.get('channelId'); }
        var sessionId = sessionIdProcessor_1.default.create({ uid: uid, channelId: channelId, sid: sid });
        return this._sessionMap.has(sessionId);
    };
    SessionManager.prototype.getSession = function (uid, channelId, sid) {
        if (uid === void 0) { uid = ''; }
        if (channelId === void 0) { channelId = userData_1.default.get('channelId'); }
        if (this.hasLocalSession(uid, channelId, sid)) {
            var sessionId = sessionIdProcessor_1.default.create({ uid: uid, channelId: channelId, sid: sid });
            return this._sessionMap.get(sessionId);
        }
        return null;
    };
    SessionManager.prototype.exchangeId = function (uid) {
        if (uid === void 0) { uid = ''; }
        var _a = uid.split('_'), pubId = _a[0], peerUid = _a[1];
        return {
            pubId: pubId,
            peerUid: peerUid
        };
    };
    SessionManager.prototype.composeId = function (_a) {
        var pid = _a.pid, peerUid = _a.peerUid;
        return pid + "_" + peerUid;
    };
    /**
     * 删除远端会话与本地会话
     *
     * @param {string} [uid=''] 用户 uid
     * @param {number} [channelId=userData.get('channelId')] 会话所属业务channelId
     * @returns Promise
     * @memberof SessionManager
     */
    SessionManager.prototype.deleteRemoteSession = function (uid, channelId, sid) {
        var _this = this;
        if (uid === void 0) { uid = ''; }
        if (channelId === void 0) { channelId = userData_1.default.get('channelId'); }
        log_1.default.log('SessionManager::deleteRemoteSession uid:' + uid + ' channelId:' + channelId + ' sid:' + sid);
        if (!this.hasLocalSession(uid, channelId, sid)) {
            log_1.default.log('SessionManager::deleteRemoteSession not found local session');
            return promise_1.default.resolve();
        }
        var session = this.getSession(uid, channelId, sid);
        var config = config_manager_1.default.getConfig();
        var lastMidMessage = message_manager_1.default.getLastMidMessage(uid, channelId, sid);
        var promise = promise_1.default.resolve();
        if (!lastMidMessage) {
            log_1.default.log('SessionManager::deleteRemoteSession not found local lastMidMessage');
            promise = promise.then(function () {
                return message_manager_1.default.fetchHistoryMessages({ uid: uid, type: session.type, channelId: session.channelId, limit: 1, sid: sid });
            });
        }
        return promise.catch(function () {
            // 兼容处理，解决群解散或者退出后，调用历史消息接口获取不到消息的问题
        }).then(function () {
            lastMidMessage = message_manager_1.default.getLastMidMessage(uid, channelId, sid);
            if (!lastMidMessage) {
                // 没有说过话
                log_1.default.log('SessionManager::deleteRemoteSession not found server lastMidMessage');
                return promise_1.default.resolve(0);
            }
            var options = {
                u: config.uid,
                ai: config.appId,
                dt: config.dt,
                chat: [__assign({ u: uid, ai: session.appId, chid: session.channelId, type: _this.getDeleteSessionType(session.type), mid: lastMidMessage ? lastMidMessage.mid : session.message.mid }, (sid ? { sid: sid } : {}))]
            };
            // PUB 单聊需要设置 pu 参数为 '0'
            if (session.isPubChat()) {
                options.chat[0].pu = '0';
            }
            // PUB 客服需要设置 pu 参数为对应 peerUid
            if (session.isCSChat()) {
                options.chat[0].u = session.pubId;
                options.chat[0].pu = session.peerUid;
            }
            return new promise_1.default(function (resolve, reject) {
                log_1.default.log('SessionManager::deleteRemoteSession request info:' + JSON.stringify(options));
                _this.mtdx.HTTP.Common.deleteRemoteSession({
                    data: options,
                    success: function (_a) {
                        var rescode = _a.rescode;
                        if (rescode === 0) {
                            log_1.default.log('SessionManager::deleteRemoteSession request success');
                            resolve();
                        }
                        else {
                            log_1.default.log('SessionManager::deleteRemoteSession request fail rescode:' + rescode);
                            reject();
                        }
                    }
                });
            });
        }).then(function () {
            log_1.default.log('SessionManager::deleteRemoteSession delete local session');
            return _this.deleteLocalSession(uid, channelId, sid);
        });
    };
    SessionManager.prototype.getDeleteSessionType = function (type) {
        switch (type) {
            case constant_1.SESSION_TYPE.CHAT2:
            case constant_1.SESSION_TYPE.CHAT: {
                return 10;
            }
            case constant_1.SESSION_TYPE.GROUP_CHAT: {
                return 11;
            }
            case constant_1.SESSION_TYPE.PUB_CHAT2:
            case constant_1.SESSION_TYPE.CS_CHAT2:
            case constant_1.SESSION_TYPE.PUB_CHAT:
            case constant_1.SESSION_TYPE.CS_CHAT: {
                return 20;
            }
        }
    };
    SessionManager.prototype.deleteLocalSessions = function (deletedSessions, shouldDeleteDBSessions) {
        var _this = this;
        if (deletedSessions === void 0) { deletedSessions = []; }
        if (shouldDeleteDBSessions === void 0) { shouldDeleteDBSessions = true; }
        log_1.default.log('SessionManager::deleteLocalSessions deletedSessions:' + deletedSessions + ' shouldDeleteDBSessions:' + shouldDeleteDBSessions);
        if (deletedSessions.length > 0) {
            deletedSessions.map(function (deletedSession) {
                _this._sessionMap.delete(deletedSession.sessionId);
                message_manager_1.default.deleteMessages(deletedSession.uid, deletedSession.channelId, deletedSession.sid);
            });
            if (shouldDeleteDBSessions) {
                DAO.removeBatch(DB_SESSION, deletedSessions.map(function (session) {
                    return session.sessionId;
                }));
            }
            event_emitter_1.default.emit(event_emitter_1.EVENT_NAME.DELETE_SESSIONS, { sessions: deletedSessions, shouldDeleteDBSessions: shouldDeleteDBSessions });
        }
    };
    SessionManager.prototype.deleteLocalSession = function (uid, channelId, sid) {
        if (uid === void 0) { uid = ''; }
        if (channelId === void 0) { channelId = userData_1.default.get('channelId'); }
        log_1.default.log('SessionManager::deleteLocalSession uid:' + uid + ' channelId:' + channelId + ' sid:' + sid);
        if (this.hasLocalSession(uid, channelId, sid)) {
            var sessionId = sessionIdProcessor_1.default.create({ uid: uid, channelId: channelId, sid: sid });
            var session = this._sessionMap.get(sessionId);
            return this.deleteLocalSessions([session], true);
        }
        else {
            log_1.default.log('SessionManager::deleteLocalSession not found session uid:' + uid + ' channelId:' + channelId + ' sid:' + sid);
        }
        return null;
    };
    SessionManager.prototype.deleteLocalSessionsByTime = function (time, shouldDeleteDBSessions, channelId) {
        if (shouldDeleteDBSessions === void 0) { shouldDeleteDBSessions = true; }
        if (channelId === void 0) { channelId = userData_1.default.get('channelId'); }
        log_1.default.log('SessionManager::deleteLocalSessionsByTime time:' + time + ' shouldDeleteDBSessions:' + shouldDeleteDBSessions);
        if (!typeChecker_1.default.isNumber(time) || time <= 0) {
            return;
        }
        return this.deleteLocalSessionsByCondition(this._sessionMap.values(), [channelId], [], time, shouldDeleteDBSessions);
    };
    // channels必须有，time为0时，删除这个channel下所有的会话和消息.types表示要删除的会话类型，为空时删除符合条件的所有会话类型
    SessionManager.prototype.deleteLocalSessionsByCondition = function (sessions, channels, types, time, shouldDeleteDBSessions) {
        var _this = this;
        if (shouldDeleteDBSessions === void 0) { shouldDeleteDBSessions = true; }
        if (!sessions || sessions.length <= 0 || !channels || channels.length <= 0) {
            return;
        }
        var deletedSessions = [];
        channels.forEach(function (channelId) {
            sessions.forEach(function (session) {
                if ((session.channelId == channelId) && (time <= 0 || session.svrTime < time)
                    && _this.isInDeleteSessionType(types, session.type)) {
                    deletedSessions.push(session);
                }
            });
            if (deletedSessions && deletedSessions.length > 0) {
                _this.deleteLocalSessions(deletedSessions, shouldDeleteDBSessions);
            }
        });
        return deletedSessions;
    };
    SessionManager.prototype.isInDeleteSessionType = function (types, typeFind) {
        if (!types || types.length <= 0) {
            return true;
        }
        var bFind = false;
        types.forEach(function (type) {
            if (type === typeFind) {
                bFind = true;
            }
        });
        return bFind;
    };
    SessionManager.prototype.retainSessionsByLength = function (length, shouldDeleteDBSessions) {
        if (length === void 0) { length = 1000; }
        if (shouldDeleteDBSessions === void 0) { shouldDeleteDBSessions = true; }
        log_1.default.log('SessionManager::retainSessionsByLength length:' + length + ' shouldDeleteDBSessions:' + shouldDeleteDBSessions);
        var deletedSessions = this.getSortedSessionList().slice(length);
        this.deleteLocalSessions(deletedSessions, shouldDeleteDBSessions);
        return deletedSessions;
    };
    SessionManager.prototype.saveSessions = function (sessions, notify, saveDB) {
        var _this = this;
        if (sessions === void 0) { sessions = []; }
        if (notify === void 0) { notify = true; }
        if (saveDB === void 0) { saveDB = true; }
        var result = [];
        if (!sessions || sessions.length === 0) {
            return;
        }
        sessions.forEach(function (session) {
            if (!session) {
                return;
            }
            result.push(session);
            _this._sessionMap.set(session.sessionId, session);
        });
        if (saveDB) {
            this._saveSessionsToDB(result);
        }
        if (notify) {
            event_emitter_1.default.emit(event_emitter_1.EVENT_NAME.UPDATE_SESSIONS, { sessions: result });
        }
    };
    SessionManager.prototype._saveSessionsToDB = function (sessions) {
        if (sessions === void 0) { sessions = []; }
        if (!this.isUseLocalDBStorage()) {
            return promise_1.default.resolve();
        }
        var sessionObj = {};
        sessions.forEach(function (session) {
            if (!session) {
                return;
            }
            sessionObj[session.sessionId] = session;
        });
        return DAO.setBatch(DB_SESSION, sessionObj);
    };
    SessionManager.prototype.sortSessionArray = function (sessionArray, reverse) {
        if (reverse === void 0) { reverse = false; }
        return sessionArray.sort(function (prev, next) {
            if (reverse) {
                return prev.time - next.time;
            }
            else {
                return next.time - prev.time;
            }
        });
    };
    SessionManager.prototype.getSortedSessionList = function () {
        var sessionArray = [];
        for (var _i = 0, _a = this._sessionMap.values(); _i < _a.length; _i++) {
            var value = _a[_i];
            if (value) {
                sessionArray.push(value);
            }
        }
        return this.sortSessionArray(sessionArray);
    };
    SessionManager.prototype.getSortedSessionListByRange = function (_a) {
        var _b = _a.start, start = _b === void 0 ? 0 : _b, _c = _a.end, end = _c === void 0 ? void 0 : _c;
        var sortedSessions = this.getSortedSessionList();
        return sortedSessions.slice(start, end);
    };
    /**
     * 从偏移量os开始，获取会话列表到指定数目
     *
     * @param {any} {os = 0, IMSessionMax = 200, PubSessionMax = 200}
     * @returns Promise<Sessions>
     * @memberof SessionManager
     */
    SessionManager.prototype.fetchSessionList = function () {
        log_1.default.warn('SessionManager::fetchSessionList 已废弃,具体使用方式建议使用初始化配置参数');
        return promise_1.default.resolve([]);
    };
    SessionManager.prototype.createSession = function (sessionDatum) {
        return models_1.Session.create(sessionDatum);
    };
    /**
     * 对外提供方法，用于创建会话
     * @param {object} datum 会话基础数据
     */
    SessionManager.prototype.createSessionByDatum = function (datum) {
        log_1.default.log('SessionManager::createSessionByDatum uid:' + datum.uid + ' type:' + datum.type + ' appId:' + datum.appId + ' channelId:' + datum.channelId);
        if (!datum.uid || !datum.type || !datum.appId || !datum.channelId === void 0) {
            log_1.default.error('SessionManager::createSessionByDatum uid|type|appId|channelId不存在，无法创建会话');
            return null;
        }
        var session = this.createSession(datum);
        this.saveSessions([session]);
        return session;
    };
    SessionManager.prototype.createSessionByMessage = function (message) {
        if (!message) {
            return null;
        }
        var belongTo = message.belongTo, svrTime = message.svrTime, time = message.time, sid = message.sid;
        if (message.isChatMessage && message.isChatMessage()) {
            return this.createSession({
                appId: message.appId,
                channelId: message.channelId,
                uid: belongTo,
                type: constant_1.SESSION_TYPE.CHAT,
                time: time,
                svrTime: svrTime,
                message: message
            });
        }
        if (message.isChatMessage2 && message.isChatMessage2()) {
            return this.createSession({
                appId: message.appId,
                channelId: message.channelId,
                uid: belongTo,
                type: constant_1.SESSION_TYPE.CHAT2,
                time: time,
                svrTime: svrTime,
                message: message,
                sid: sid
            });
        }
        if (message.isGroupChatMessage && message.isGroupChatMessage()) {
            return this.createSession({
                appId: message.appId,
                channelId: message.channelId,
                uid: belongTo,
                type: constant_1.SESSION_TYPE.GROUP_CHAT,
                time: time,
                svrTime: svrTime,
                message: message,
                sid: sid
            });
        }
        if (message.isPubChatMessage && message.isPubChatMessage()) {
            return this.createSession({
                appId: 0,
                channelId: message.channelId,
                uid: belongTo,
                type: constant_1.SESSION_TYPE.PUB_CHAT,
                time: time,
                svrTime: svrTime,
                message: message
            });
        }
        if (message.isPubChatMessage2 && message.isPubChatMessage2()) {
            return this.createSession({
                appId: 0,
                channelId: message.channelId,
                uid: belongTo,
                type: constant_1.SESSION_TYPE.PUB_CHAT2,
                time: time,
                svrTime: svrTime,
                message: message,
                sid: sid
            });
        }
        if (message.isCSChatMessage && message.isCSChatMessage()) {
            var pubId = message.pubId, peerUid = message.peerUid;
            return this.createSession({
                appId: 0,
                channelId: message.channelId,
                uid: belongTo,
                type: constant_1.SESSION_TYPE.CS_CHAT,
                time: time,
                svrTime: svrTime,
                pubId: pubId,
                peerUid: peerUid,
                message: message
            });
        }
        if (message.isCSChatMessage2 && message.isCSChatMessage2()) {
            var pubId = message.pubId, peerUid = message.peerUid;
            return this.createSession({
                appId: 0,
                channelId: message.channelId,
                sid: message.sid,
                uid: belongTo,
                type: constant_1.SESSION_TYPE.CS_CHAT2,
                time: time,
                svrTime: svrTime,
                pubId: pubId,
                peerUid: peerUid,
                message: message
            });
        }
    };
    SessionManager.prototype.updateSessionByMessageAndSave = function (message) {
        var session = this.updateSessionByMessage(message);
        this.saveSessions([session]);
    };
    SessionManager.prototype.updateSessionByMessage = function (message) {
        // Log.log('SessionManager::updateSessionByMessage message info:' + message);
        var uid = message.belongTo;
        var channelId = message.channelId;
        var sid = message.sid;
        var session = null;
        // 发送中消息不更新预览
        if (message.status === models_1.Message.STATUS.STATUS_SENT) {
            log_1.default.log('SessionManager::updateSessionByMessage message.status === Message.STATUS.STATUS_SENT message info:' + message);
            return;
        }
        var hasLocalSession = false;
        if (this.hasLocalSession(uid, channelId, sid)) {
            hasLocalSession = true;
            session = this.getSession(uid, channelId, sid);
        }
        else {
            session = this.createSessionByMessage(message);
            if (session) {
                this.saveSessions([session], false);
            }
            else {
                log_1.default.log('SessionManager::updateSessionByMessage not create session by message info:' + message);
                return;
            }
        }
        var beforeLog = 'SessionManager::updateSessionByMessage begin session info:' + session +
            ' messagetype:' + message.type + ' message.from:' + message.from
            + ' hasLocalSession:' + hasLocalSession;
        var afterLog = '';
        var beforeUnreads = session.unreads;
        if (message_manager_1.default.getMessages(session.uid, session.channelId, session.sid).length < session.unreads && message.svrTime > session.readTime) {
            // 此判断条件是为了解决上次已经计算完未读数但是本地又没有消息的场景
            //（比如登录成功后会话是从数据库读取出来的，但是登录成功的会话未读数还还没有计算完成就收到了在线消息就会触发到这里。
            // 又比如本地读取出来的会话已经不再服务端的会话列表中了 ，但是有未读数）
            // 所以针对这种场景暂时采用+1方法(撤回-1),并且在下次重新计算未读数
            //（登录成功会重新计算未读数，但是对于本地读取出来的会话已经不再服务端的会话列表中了这种场景是不处理的）时进行校准
            if (message.type === constant_1.MESSAGE_TYPE.MSG_TYPE_EVENT || message.from == config_manager_1.default.getConfig().uid) {
                // 撤回消息和发送的消息不需要进行未读数处理
                afterLog = ' case-one event message or send message ' + ' type:' + message.type + ' message.from:' + config_manager_1.default.getConfig().uid;
            }
            else {
                if (message.isCancel) {
                    if (session.unreads > 0) {
                        session.unreads -= 1;
                        afterLog = ' case-one cancel message sub unread' + ' cur session.unreads:' + beforeUnreads + ' result:' + session.unreads;
                    }
                }
                else {
                    session.unreads += 1;
                    afterLog = ' case-one normal message add unread' + ' cur session.unreads:' + beforeUnreads + ' result:' + session.unreads;
                }
            }
            session.setCountUnreadFlag(false);
        }
        else {
            // 登录成功后会话的未读数根据拉取的消息已经计算完成场景会走到这个逻辑
            session.unreads = this.countUnreadByMessages({ session: session });
            afterLog = ' case-two cal unread by messages' + ' cur session.unreads:' + beforeUnreads + ' result:' + session.unreads;
        }
        if (session.time < message.time) {
            session.time = message.time;
        }
        if (session.svrTime < message.svrTime) {
            session.svrTime = message.svrTime;
        }
        var lastMessage = message_manager_1.default.getLastMessage(uid, channelId, sid);
        session.message = lastMessage ? lastMessage : message;
        log_1.default.log(beforeLog + afterLog + ' end session info:' + session);
        return session;
    };
    SessionManager.prototype._parseIMRead = function (_a) {
        var _b = _a.uid, uid = _b === void 0 ? '' : _b, _c = _a.deviceType, deviceType = _c === void 0 ? 0 : _c, _d = _a.msgUuid, msgUuid = _d === void 0 ? '' : _d, _e = _a.syncReadItems, syncReadItems = _e === void 0 ? [] : _e;
        return new models_1.Read({
            uid: uid,
            deviceType: deviceType,
            msgUuid: msgUuid,
            syncReadItems: syncReadItems.map(function (element) {
                return __assign({ uid: element.chatId, channelId: element.channel, peerAppId: element.peerAppId, time: parseInt(element.stamp), svrTime: parseInt(element.sts), 
                    //1为单聊，2为群聊
                    sessionType: element.type === 1 ? (element.sid ? constant_1.SESSION_TYPE.CHAT2 : constant_1.SESSION_TYPE.CHAT) : constant_1.SESSION_TYPE.GROUP_CHAT }, (constant_1.SESSION_TYPE.CHAT2 ? { sid: element.sid } : {}));
            })
        });
    };
    SessionManager.prototype._parsePubRead = function (_a) {
        var _b = _a.uid, uid = _b === void 0 ? '' : _b, _c = _a.deviceType, deviceType = _c === void 0 ? 0 : _c, _d = _a.msgUuid, msgUuid = _d === void 0 ? '' : _d, _e = _a.syncReadItems, syncReadItems = _e === void 0 ? [] : _e;
        return new models_1.Read({
            uid: uid,
            deviceType: deviceType,
            msgUuid: msgUuid,
            syncReadItems: syncReadItems.map(function (element) {
                var item = {
                    channelId: element.channel,
                    pubId: element.chatId,
                    peerUid: element.peerUid,
                    peerAppId: element.peerAppId,
                    time: parseInt(element.stamp),
                    svrTime: parseInt(element.sts),
                    //1为Pub单聊单聊，2为客服会话
                    sessionType: element.type === 1 ? (element.sid ? constant_1.SESSION_TYPE.PUB_CHAT2 : constant_1.SESSION_TYPE.PUB_CHAT) : (element.sid ? constant_1.SESSION_TYPE.CS_CHAT2 : constant_1.SESSION_TYPE.CS_CHAT),
                    sid: element.sid || '',
                };
                return __assign(__assign({}, item), { uid: (item.sessionType === constant_1.SESSION_TYPE.PUB_CHAT || item.sessionType === constant_1.SESSION_TYPE.PUB_CHAT2) ? element.chatId : element.chatId + "_" + element.peerUid });
            })
        });
    };
    SessionManager.prototype.isShouldCountUnread = function (session, message) {
        if (!session || !this.hasLocalSession(session.uid, session.channelId, session.sid)) {
            return false;
        }
        // 撤回消息不计入未读数;EVENT 消息不计入未读数
        if (message.isCancel || message.type === constant_1.MESSAGE_TYPE.MSG_TYPE_EVENT) {
            return false;
        }
        if (message.svrTime > session.readTime && message.from !== config_manager_1.default.getConfig().uid && session.channelId === message.channelId) {
            return true;
        }
        return false;
    };
    SessionManager.prototype.updateSessionsByReadsAndSave = function (_a) {
        var _this = this;
        var _b = _a.readItems, readItems = _b === void 0 ? [] : _b;
        // Log.log('SessionManager::updateSessionsByReadsAndSave info:' + readItems)
        var sessions = [];
        readItems.forEach(function (readItem) {
            var _a = sessionIdProcessor_1.default.parseSessionId(readItem.sessionId), uid = _a.uid, channelId = _a.channelId, sid = _a.sid;
            if (!_this.hasLocalSession(uid, channelId, sid)) {
                return;
            }
            sessions.push(_this.updateSessionByRead(readItem));
        });
        this.saveSessions(sessions);
    };
    SessionManager.prototype.updateSessionByRead = function (readItem) {
        if (!readItem) {
            return;
        }
        var sessionId = readItem.sessionId;
        var _a = sessionIdProcessor_1.default.parseSessionId(sessionId), uid = _a.uid, channelId = _a.channelId, sid = _a.sid;
        var session = this.getSession(uid, channelId, sid);
        var beginLog = 'SessionManager::updateSessionByRead begin session:' + session;
        if (readItem.svrTime > session.readTime) {
            session.readTime = readItem.svrTime;
            session.unreads = this.countUnreadByMessages({ session: session });
        }
        log_1.default.log(beginLog + ' end session:' + session);
        return session;
    };
    SessionManager.prototype.updateEmptySession = function (uid, channelId, sid) {
        if (uid === void 0) { uid = ''; }
        if (channelId === void 0) { channelId = userData_1.default.get('channelId'); }
        var session = this.getSession(uid, channelId, sid);
        session.unreads = session.unreads = this.countUnreadByMessages({ session: session });
        session.readTime = session.svrTime;
        this.saveSessions([session]);
    };
    /**
     * @param uid 会话id
     * @param peerAppId 对端 APPID
     * @param channelId 强制指定发送是ChannelId字段
     * @param {any} {uid, channelId}
     * @memberof SessionManager
     */
    SessionManager.prototype.readSession = function (_a) {
        var _this = this;
        var _b = _a.uid, uid = _b === void 0 ? '' : _b, _c = _a.peerAppId, peerAppId = _c === void 0 ? 0 : _c, _d = _a.channelId, channelId = _d === void 0 ? userData_1.default.get('channelId') : _d, sid = _a.sid;
        // Log.log('SessionManager::readSession uid:' + uid + ' peerAppId:' + peerAppId + ' channelId:' + channelId + ' sid:' + sid)
        if (!this.hasLocalSession(uid, channelId, sid)) {
            log_1.default.log('SessionManager::readSession local not found sessin uid:' + uid + ' channelId:' + channelId + ' sid:' + sid);
            return;
        }
        var session = this.getSession(uid, channelId, sid);
        var lastMidMessage = message_manager_1.default.getLastMidMessage(uid, channelId, sid);
        var promise = promise_1.default.resolve();
        if (!lastMidMessage) {
            lastMidMessage = session.message;
        }
        if (!lastMidMessage || !lastMidMessage.svrTime) {
            log_1.default.log('SessionManager::readSession not found local lastMidMessage');
            promise = promise.then(function () {
                return message_manager_1.default.fetchHistoryMessages({ uid: uid, type: session.type, channelId: channelId, limit: 1, sid: sid });
            });
        }
        promise.then(function () {
            if (!lastMidMessage) {
                lastMidMessage = lastMidMessage = message_manager_1.default.getLastMidMessage(uid, channelId, sid);
            }
            if (lastMidMessage) {
                var readArrayObject = {
                    chatId: uid,
                    channelId: channelId,
                    sessionType: lastMidMessage.sessionType,
                    time: lastMidMessage.svrTime,
                    svrTime: lastMidMessage.svrTime,
                    peerAppId: peerAppId ? peerAppId : session.appId,
                    sid: sid
                };
                // Log.log('SessionManager::readSession sendRead info:' + JSON.stringify(readArrayObject))
                _this.sendRead({
                    sessionType: lastMidMessage.sessionType,
                    readArray: [readArrayObject]
                });
            }
            else {
                log_1.default.log('SessionManager::readSession updateEmptySession');
                _this.updateEmptySession(uid, channelId, sid);
            }
        });
    };
    SessionManager.prototype.sendRead = function (_a) {
        var _this = this;
        var _b = _a.sessionType, sessionType = _b === void 0 ? constant_1.SESSION_TYPE.CHAT : _b, _c = _a.uuid, uuid = _c === void 0 ? void 0 : _c, _d = _a.readArray, readArray = _d === void 0 ? [] : _d;
        if (readArray.length === 0) {
            return;
        }
        var read;
        switch (sessionType) {
            case constant_1.SESSION_TYPE.CHAT:
            case constant_1.SESSION_TYPE.CHAT2:
            case constant_1.SESSION_TYPE.GROUP_CHAT: {
                read = this.sendIMRead({ uuid: uuid, readArray: readArray }, sessionType);
                break;
            }
            case constant_1.SESSION_TYPE.PUB_CHAT:
            case constant_1.SESSION_TYPE.PUB_CHAT2:
            case constant_1.SESSION_TYPE.CS_CHAT2:
            case constant_1.SESSION_TYPE.CS_CHAT: {
                read = this.sendPubRead({ uuid: uuid, readArray: readArray }, sessionType);
                break;
            }
        }
        // Log.log('SessionManager::sendRead sessionType:' + sessionType + ' uuid:' + uuid + ' read.uuid:' + read.uuid + ' readArray:' + readArray)
        this.updateSessionsByReadsAndSave(read);
        var unsentRead = this._readSendMap.get(read.uuid);
        var count = 1;
        if (unsentRead) {
            if (unsentRead.timer) {
                clearTimeout(unsentRead.timer);
            }
            count = unsentRead.count + 1;
        }
        if (count < 3) {
            this._readSendMap.set(read.uuid, {
                count: count,
                uuid: read.uuid,
                readArray: readArray,
                timer: setTimeout(function () {
                    log_1.default.log('SessionManager::sendRead timeout read.uuid:' + read.uuid + ' count:' + count);
                    _this.sendRead({ sessionType: sessionType, uuid: read.uuid, readArray: readArray });
                }, READ_RETRY_TIME)
            });
        }
    };
    SessionManager.prototype.sendIMRead = function (_a, sessionType) {
        var _b = _a.uuid, uuid = _b === void 0 ? void 0 : _b, _c = _a.readArray, readArray = _c === void 0 ? [] : _c;
        log_1.default.log('SessionManager::sendIMRead sessionType:' + sessionType + ' uuid:' + uuid + ' readArray:' + readArray);
        var readInstance = create_readitem_1.createIMReadProtocol({
            sessionType: sessionType,
            uuid: uuid,
            readData: readArray
        });
        // 增加按模块加载容错处理
        if (this.mtdx.imSDK) {
            this.mtdx.imSDK.send(readInstance);
            return this._parseIMRead(readInstance);
        }
        return {};
    };
    SessionManager.prototype.sendPubRead = function (_a, sessionType) {
        var _this = this;
        var _b = _a.uuid, uuid = _b === void 0 ? void 0 : _b, _c = _a.readArray, readArray = _c === void 0 ? [] : _c;
        log_1.default.log('SessionManager::sendPubRead sessionType:' + sessionType + ' uuid:' + uuid + ' readArray:' + readArray);
        var readInstance = create_readitem_1.createPubReadProtocol({
            sessionType: sessionType,
            uuid: uuid,
            readData: readArray.map(function (readObj) {
                // chatId即为pubId，此处可以兼容处理 PUB 单聊情况，peerUid为空
                var _a = _this.exchangeId(readObj.chatId), pubId = _a.pubId, peerUid = _a.peerUid;
                return __assign(__assign({}, readObj), { chatId: pubId, peerUid: peerUid });
            })
        });
        // 增加按模块加载容错处理
        if (this.mtdx.pubSDK) {
            this.mtdx.pubSDK.send(readInstance);
            return this._parsePubRead(readInstance);
        }
        return {};
    };
    SessionManager.prototype.handleReadAck = function (_a) {
        // Log.log('SessionManager::handleReadAck uuid:' + uuid)
        var _b = _a.uuid, uuid = _b === void 0 ? void 0 : _b;
        var readHandle = this._readSendMap.get(uuid);
        if (readHandle) {
            clearTimeout(readHandle.timer);
            this._readSendMap.delete(uuid);
        }
    };
    SessionManager.prototype.isUseLocalDBStorage = function () {
        // 在web端假如业务没有配置过这个属性（默认就是没有配置这个属性）或者这个属性配置为true则使用本地DB存储，只有当这个属性配置为false才不使用本地DB存储。
        // 在小程序端，由于小程序根本就没有DB，所以不管这个属性如何配置都不会使用本地存储的。
        return userData_1.default.get('shouldGetSessionFromDB') === undefined || userData_1.default.get('shouldGetSessionFromDB') === true;
    };
    SessionManager.prototype.fetchRemoteSessionListAndCountUnreadByHistoryMessages = function (_a) {
        var _this = this;
        var _b = _a.IMStartTime, IMStartTime = _b === void 0 ? Date.now() - this._IMTimeRange : _b, _c = _a.PubStartTime, PubStartTime = _c === void 0 ? Date.now() - this._PubTimeRange : _c;
        log_1.default.log('SessionManager::fetchRemoteSessionListAndCountUnreadByHistoryMessages IMStartTime:' + IMStartTime + ' PubStartTime:' + PubStartTime);
        var existSessions = this._sessionMap.entries();
        var existReadTime = {};
        // 本地离线操作的已读时间需要在联网后同步给服务端
        existSessions.forEach(function (_a) {
            var sessionId = _a[0], session = _a[1];
            existReadTime[sessionId] = {
                sessionId: sessionId,
                sessionType: session.sessionType,
                svrTime: session.readTime
            };
        });
        return promise_1.default.all([
            // 第一次初始化从本地 DB 读取数据,断线重连时,内存数据和本地 DB 数据一致,不需要再从本地DB读数据
            this._isFirstInit ? this.getSessionFromDB() : promise_1.default.resolve(this._sessionMap.values()),
            this.fetchRemoteSessionListByTime({ IMStartTime: IMStartTime, PubStartTime: PubStartTime }),
            this.fetchRemoteReadTimeByTime({ IMStartTime: IMStartTime, PubStartTime: PubStartTime })
        ]).then(function (_a) {
            var localSessions = _a[0], sessions = _a[1], remoteReadItemData = _a[2];
            log_1.default.log('SessionManager::fetchRemoteSessionListAndCountUnreadByHistoryMessages result localSessions:' + (localSessions ? localSessions.length : 0)
                + ' remoteReadItemData:' + (remoteReadItemData ? Object.keys(remoteReadItemData).length : 0)
                + ' existReadTime:' + (existReadTime ? Object.keys(existReadTime).length : 0)
                + ' sessions:' + message_util_1.default.getSessionArrayPrint(sessions));
            _this._isFirstInit = false;
            var readItemData = _this.mergeLocalAndRemoteReadItemDataAndUpdateServer({ existReadTime: existReadTime, remoteReadItemData: remoteReadItemData });
            var unreadSessions = _this.getUnreadSessions({ sessions: sessions, localSessions: localSessions, readItemData: readItemData });
            if (_this.isUseLocalDBStorage()) {
                _this._loadNotExistSessionFromDB({ localSessions: localSessions });
            }
            if (_this._sessionMap.size === 0) {
                event_emitter_1.default.emit(event_emitter_1.EVENT_NAME.EMPTY_SESSIONS);
            }
            event_emitter_1.default.emit(event_emitter_1.EVENT_NAME.SESSIONS_LOAD_FINISHED);
            if (unreadSessions && unreadSessions.length > 0) {
                log_1.default.log('SessionManager::fetchRemoteSessionListAndCountUnreadByHistoryMessages unreadSessions:' + message_util_1.default.getSessionArrayPrint(unreadSessions));
                return _this.fetchHistoryMessagesAndCountUnread({ unreadSessions: unreadSessions });
            }
            else {
                log_1.default.log('SessionManager::fetchRemoteSessionListAndCountUnreadByHistoryMessages unreadSessions 0');
                return promise_1.default.resolve();
            }
        }).catch(function (e) {
            log_1.default.error('SessionManager::fetchRemoteSessionListAndCountUnreadByHistoryMessages' + e);
        });
    };
    SessionManager.prototype.getUnreadSessions = function (_a) {
        var _b = _a.sessions, sessions = _b === void 0 ? [] : _b, _c = _a.localSessions, localSessions = _c === void 0 ? [] : _c, _d = _a.readItemData, readItemData = _d === void 0 ? {} : _d;
        log_1.default.log('SessionManager::getUnreadSessions');
        // 需要保存但不触发更新的会话:只有已读时间更新
        var shouldSaveSessions = [];
        // 需要保存同时出发更新的会话:未读数有变化
        var shouldSaveAndNotifiedSessions = [];
        var unreadSessions = [];
        sessions.forEach(function (session) {
            var readItem = readItemData[session.sessionId];
            var existLocalSession = localSessions.find(function (localSession) {
                return session.sessionId === localSession.sessionId;
            });
            // 只有下述条件满足,就不需要去拉历史消息计算未读数:本地会话存在且本地会话上次已经计算过未读数并且本地会话最后一条消息为最新且(服务端没有 readTime|服务端的 readTime 等于本地 readTime)
            if (existLocalSession && existLocalSession.isCountUnread() && existLocalSession.svrTime === session.svrTime
                && ((readItem && readItem.svrTime === existLocalSession.readTime) || !readItem)
                && existLocalSession.message && session.message && existLocalSession.message.isCancel === session.message.isCancel) {
                if (existLocalSession.unreads > 0) {
                    shouldSaveAndNotifiedSessions.push(existLocalSession);
                }
                else {
                    shouldSaveSessions.push(existLocalSession);
                }
                return;
            }
            // 此处只更新已读时间,后续未读数等拉取历史消息计算后更新
            if (readItem && readItem.svrTime > session.readTime) {
                session.readTime = readItem.svrTime;
            }
            if (session.svrTime > session.readTime) {
                session.setCountUnreadFlag(false);
                unreadSessions.push(session);
            }
            // 本地有未读数的话,先展示本地未读数数据,避免历史消息接口计算异常导致无未读数提醒(此时展示未读数仅作为提醒用户,宁可多提示,也不要接口失败时遗漏)
            if (existLocalSession && existLocalSession.unreads > 0 && (!readItem || existLocalSession.readTime === readItem.readTime)) {
                session.unreads = existLocalSession.unreads;
                shouldSaveAndNotifiedSessions.push(session);
            }
            else {
                shouldSaveSessions.push(session);
            }
        });
        this.saveSessions(shouldSaveSessions, false);
        this.saveSessions(shouldSaveAndNotifiedSessions);
        return unreadSessions;
    };
    /**
     * 将从远端获取不到且本地 DB 存在的会话列表数据放入内存中,此时数据已经读进内存,所以是同步方法
     *
     * @param {*} {localSessions}
     * @memberof SessionManager
     */
    SessionManager.prototype._loadNotExistSessionFromDB = function (_a) {
        var _this = this;
        var localSessions = _a.localSessions;
        var notExistRemoteSessions = localSessions.filter(function (session) {
            return !_this.hasLocalSession(session.uid, session.channelId, session.sid);
        });
        log_1.default.log('SessionManager::_loadNotExistSessionFromDB notExistRemoteSessions size:' + (notExistRemoteSessions ? notExistRemoteSessions.length : 0));
        var localSessionNumber = userData_1.default.get('localSessionNumber');
        if (localSessionNumber && typeChecker_1.default.isNumber(localSessionNumber)) {
            if (localSessionNumber < notExistRemoteSessions.length) {
                var sortedSessions = this.sortSessionArray(notExistRemoteSessions);
                this.deleteLocalSessions(sortedSessions.slice(localSessionNumber));
                notExistRemoteSessions = sortedSessions.slice(0, localSessionNumber);
            }
        }
        this.saveSessions(notExistRemoteSessions, true, false);
    };
    SessionManager.prototype.fetchRemoteSessionListByTime = function (_a) {
        var _b = _a.IMStartTime, IMStartTime = _b === void 0 ? Date.now() - this._IMTimeRange : _b, _c = _a.PubStartTime, PubStartTime = _c === void 0 ? Date.now() - this._PubTimeRange : _c;
        log_1.default.log('SessionManager::fetchRemoteSessionListByTime IMStartTime:' + IMStartTime + ' PubStartTime:' + PubStartTime);
        return promise_1.default.all([
            ( true) ? this.fetchIMRemoteSessionListByTime({ startTime: IMStartTime }) : undefined,
            ( true) ? this.fetchPubRemoteSessionListByTime({ startTime: PubStartTime }) : undefined
        ]).then(function (_a) {
            var IMSessions = _a[0], PubSessions = _a[1];
            log_1.default.log('SessionManager::fetchRemoteSessionListByTime result IMSessions:' + (IMSessions ? IMSessions.length : 0) + ' PubSessions:' + (PubSessions ? PubSessions.length : 0));
            var sessions = __spreadArrays(IMSessions, PubSessions);
            return sessions;
        }).catch(function (e) {
            log_1.default.error('SessionManager::fetchRemoteSessionListByTime 会话列表加载失败 e:' + e);
            return [];
        });
    };
    SessionManager.prototype.fetchIMRemoteSessionListByTime = function (_a) {
        var _this = this;
        var startTime = _a.startTime, _b = _a.endTime, endTime = _b === void 0 ? BIG_TIME : _b;
        if (this._IMTimeRange === 0) {
            log_1.default.log('SessionManager::fetchIMRemoteSessionListByTime _IMTimeRange 0');
            return promise_1.default.resolve([]);
        }
        else {
            this._lastFetchIMSessionListTime = startTime;
            log_1.default.log('SessionManager::fetchIMRemoteSessionListByTime startTime:' + startTime + ' endTime:' + endTime);
            return new promise_1.default(function (resolve, reject) {
                _this.fetchIMRemoteSessionListByTimeByCycle({ prev: new map_1.default(), startTime: startTime, endTime: endTime, resolve: resolve, reject: reject });
            }).then(function (sessionsMap) {
                return sessionsMap.values();
            });
        }
    };
    /**
     * 循环拉取 IM 会话列表, 采用分页方法,一次拉取 1000 条
     *
     * @param {*} {prev, startTime, endTime, resolve, reject}
     * @memberof SessionManager
     */
    SessionManager.prototype.fetchIMRemoteSessionListByTimeByCycle = function (_a) {
        var _this = this;
        var prev = _a.prev, startTime = _a.startTime, endTime = _a.endTime, resolve = _a.resolve, reject = _a.reject;
        log_1.default.log('SessionManager::fetchIMRemoteSessionListByTimeByCycle prev:' +
            (prev ? prev.size : 0) + ' startTime:' + startTime + ' endTime:' + endTime
            + ' _imSessionListRetryTime:' + this._imSessionListRetryTime);
        message_manager_1.default.fetchIMRemoteMessagesByTime({ startTime: startTime, endTime: endTime }).then(function (_a) {
            var _b = _a.IMRemoteMessages, IMRemoteMessages = _b === void 0 ? [] : _b, next = _a.next;
            var shouldSavedSessionsMap = new map_1.default();
            IMRemoteMessages.forEach(function (message) {
                if (!prev.has(message.sessionId) || prev.has(message.sessionId) && prev.get(message.sessionId).svrTime < message.svrTime) {
                    var session = _this.createSessionByMessage(message);
                    prev.set(message.sessionId, session);
                    shouldSavedSessionsMap.set(message.sessionId, session);
                }
            });
            log_1.default.log('SessionManager::fetchIMRemoteSessionListByTimeByCycle next:' + next
                + ' IMRemoteMessages:' + (IMRemoteMessages ? IMRemoteMessages.length : 0)
                + ' prev:' + (prev ? prev.size : 0)
                + ' shouldSavedSessions:' + (shouldSavedSessionsMap ? shouldSavedSessionsMap.size : 0));
            _this.saveSessions(shouldSavedSessionsMap.values());
            if (next > 0) {
                _this.fetchIMRemoteSessionListByTimeByCycle({ prev: prev, startTime: startTime, endTime: next, resolve: resolve, reject: reject });
            }
            else {
                resolve(prev);
            }
        }).catch(function (e) {
            log_1.default.error('SessionManager::fetchIMRemoteSessionListByTimeByCycle IM 会话列表获取失败 e:', e);
            if (_this._imSessionListRetryTime < SESSION_LIST_RETRY_MAX_TIMES) {
                _this._imSessionListRetryTime++;
                _this.fetchIMRemoteSessionListByTimeByCycle({ prev: prev, startTime: startTime, endTime: endTime, resolve: resolve, reject: reject });
            }
            else {
                resolve(prev);
            }
        });
    };
    /**
     * Pub 会话列表只存储 1000 个,不需要循环拉取
     *
     * @param {*} {startTime, endTime = void 0}
     * @returns
     * @memberof SessionManager
     */
    SessionManager.prototype.fetchPubRemoteSessionListByTime = function (_a) {
        var _this = this;
        var startTime = _a.startTime, _b = _a.endTime, endTime = _b === void 0 ? BIG_TIME : _b;
        if (this._PubTimeRange === 0) {
            log_1.default.log('SessionManager::fetchPubRemoteSessionListByTime _PubTimeRange 0');
            return promise_1.default.resolve([]);
        }
        else {
            this._lastFetchPubSessionListTime = startTime;
            log_1.default.log('SessionManager::fetchPubRemoteSessionListByTime startTime:' + startTime + ' endTime:' + endTime);
            return new promise_1.default(function (resolve, reject) {
                _this.fetchPUBRemoteSessionListByTimeByCycle({ prev: new map_1.default(), startTime: startTime, endTime: endTime, resolve: resolve, reject: reject });
            }).then(function (sessionsMap) {
                return sessionsMap.values();
            });
        }
    };
    SessionManager.prototype.fetchPUBRemoteSessionListByTimeByCycle = function (_a) {
        var _this = this;
        var prev = _a.prev, startTime = _a.startTime, endTime = _a.endTime, resolve = _a.resolve, reject = _a.reject;
        log_1.default.log('SessionManager::fetchPUBRemoteSessionListByTimeByCycle prev:' +
            (prev ? prev.size : 0) + ' startTime:' + startTime + ' endTime:' + endTime
            + ' _pubSessionListRetryTime:' + this._pubSessionListRetryTime);
        message_manager_1.default.fetchPubRemoteMessagesByTime({ startTime: startTime, endTime: endTime }).then(function (_a) {
            var _b = _a.PubRemoteMessages, PubRemoteMessages = _b === void 0 ? [] : _b, next = _a.next;
            var shouldSavedSessionsMap = new map_1.default();
            PubRemoteMessages.forEach(function (message) {
                if (!prev.has(message.sessionId) || prev.has(message.sessionId) && prev.get(message.sessionId).svrTime < message.svrTime) {
                    var session = _this.createSessionByMessage(message);
                    prev.set(message.sessionId, session);
                    shouldSavedSessionsMap.set(message.sessionId, session);
                }
            });
            log_1.default.log('SessionManager::fetchPUBRemoteSessionListByTimeByCycle next:' + next
                + ' PubRemoteMessages:' + (PubRemoteMessages ? PubRemoteMessages.length : 0)
                + ' prev:' + (prev ? prev.size : 0)
                + ' shouldSavedSessions:' + (shouldSavedSessionsMap ? shouldSavedSessionsMap.size : 0));
            _this.saveSessions(shouldSavedSessionsMap.values());
            if (next > 0) {
                _this.fetchPUBRemoteSessionListByTimeByCycle({ prev: prev, startTime: startTime, endTime: next, resolve: resolve, reject: reject });
            }
            else {
                resolve(prev);
            }
        }).catch(function (e) {
            log_1.default.error('SessionManager::fetchPUBRemoteSessionListByTimeByCycle PUB 会话列表获取失败 e:', e);
            if (_this._pubSessionListRetryTime < SESSION_LIST_RETRY_MAX_TIMES) {
                _this._pubSessionListRetryTime++;
                _this.fetchPUBRemoteSessionListByTimeByCycle({ prev: prev, startTime: startTime, endTime: endTime, resolve: resolve, reject: reject });
            }
            else {
                resolve(prev);
            }
        });
    };
    /**
     * 从本地 DB 读取会话列表数据,这一步不保存,在远端会话列表返回去重后保存,避免未读数跳动问题
     * @returns Promise
     * @memberof SessionManager
     */
    SessionManager.prototype.getSessionFromDB = function () {
        var _this = this;
        return DAO.getAll(DB_SESSION).then(function (res) {
            var sessions = [];
            var shouldUpdateUids = [];
            var shouldUpdateSessionInDB = [];
            if (!_this.isUseLocalDBStorage()) {
                return sessions;
            }
            // 需要全量数据,本地数据优化接口请求数量
            for (var i in res) {
                var sessionDatum = res[i];
                var session = _this.createSession(sessionDatum);
                if (!session) {
                    continue;
                }
                sessions.push(session);
                // 处理更新数据库 key 时删除旧数据，更新新数据问题
                if (!sessionIdProcessor_1.default.isSessionId(i)) {
                    shouldUpdateUids.push(session.uid);
                    shouldUpdateSessionInDB.push(session);
                }
            }
            if (shouldUpdateSessionInDB.length > 0) {
                // 处理更新数据库 key 时删除旧数据，更新新数据问题
                return DAO.removeBatch(DB_SESSION, shouldUpdateUids).then(function () {
                    _this._saveSessionsToDB(shouldUpdateSessionInDB);
                    return sessions;
                });
            }
            else {
                return sessions;
            }
        });
    };
    SessionManager.prototype.fetchRemoteReadTimeByTime = function (_a) {
        var _b = _a.IMStartTime, IMStartTime = _b === void 0 ? Date.now() - this._IMTimeRange : _b, _c = _a.PubStartTime, PubStartTime = _c === void 0 ? Date.now() - this._PubTimeRange : _c;
        log_1.default.log('SessionManager::fetchRemoteReadTimeByTime IMStartTime:' +
            IMStartTime + ' PubStartTime:' + PubStartTime);
        return promise_1.default.all([
            ( true) ? this.fetchIMRemoteReadTimeByTime({ startTime: IMStartTime }) : undefined,
            ( true) ? this.fetchPubRemoteReadTimeByTime({ startTime: PubStartTime }) : undefined
        ]).then(function (_a) {
            var _b = _a[0], IMRead = _b[0], IMRead2 = _b[1], _c = _a[1], PubRead = _c[0], PubRead2 = _c[1];
            var readItemData = {};
            if (IMRead && IMRead.readItems) {
                IMRead.readItems.forEach(function (readItem) {
                    readItemData[readItem.sessionId] = readItem;
                });
            }
            if (IMRead2 && IMRead2.readItems) {
                IMRead2.readItems.forEach(function (readItem) {
                    readItemData[readItem.sessionId] = readItem;
                });
            }
            if (PubRead && PubRead.readItems) {
                PubRead.readItems.forEach(function (readItem) {
                    readItemData[readItem.sessionId] = readItem;
                });
            }
            if (PubRead2 && PubRead2.readItems) {
                PubRead2.readItems.forEach(function (readItem) {
                    readItemData[readItem.sessionId] = readItem;
                });
            }
            log_1.default.log('SessionManager::fetchRemoteReadTimeByTime '
                + ' IMRead:' + (IMRead && IMRead.readItems ? IMRead.readItems.length : 0)
                + ' IMRead2:' + (IMRead2 && IMRead2.readItems ? IMRead2.readItems.length : 0)
                + ' PubRead:' + (PubRead && PubRead.readItems ? PubRead.readItems.length : 0)
                + ' PubRead2:' + (PubRead2 && PubRead2.readItems ? PubRead2.readItems.length : 0)
                + ' readItemData:' + (readItemData ? Object.keys(readItemData).length : 0));
            return readItemData;
        }).catch(function (e) {
            log_1.default.error('SessionManager::fetchRemoteReadTimeByTime 已读时间加载失败 e:', e);
            return {};
        });
    };
    SessionManager.prototype.fetchIMRemoteReadTimeByTime = function (_a) {
        var _this = this;
        var _b = _a.startTime, startTime = _b === void 0 ? Date.now() - this._IMTimeRange : _b;
        if (this._IMTimeRange === 0) {
            log_1.default.log('SessionManager::fetchIMRemoteReadTimeByTime _IMTimeRange 0');
            return promise_1.default.resolve([{}, {}]);
        }
        else {
            return new promise_1.default(function (resolve, reject) {
                log_1.default.log('SessionManager::fetchIMRemoteReadTimeByTime startTime:' + startTime);
                _this.mtdx.HTTP.Msg.chats({
                    data: {
                        ts: startTime,
                        type: 1 // 支持自定义会话为 1
                    },
                    success: function (result) {
                        if (0 !== result.rescode) {
                            log_1.default.log('SessionManager::fetchIMRemoteReadTimeByTime fail rescode:' + result.rescode);
                            return reject({ code: result.rescode, message: result });
                        }
                        else {
                            var syncData = result.data.sync_data ? _this._parseIMRead(result.data.sync_data) : {};
                            var syncData2 = result.data.sync_data2 ? _this._parseIMRead(result.data.sync_data2) : {};
                            log_1.default.log('SessionManager::fetchIMRemoteReadTimeByTime success rescode:' + result.rescode
                                + ' syncData:' + (syncData && syncData.readItems ? syncData.readItems.length : 0)
                                + ' syncData2:' + (syncData2 && syncData2.readItems ? syncData2.readItems.length : 0));
                            resolve([
                                syncData,
                                syncData2
                            ]);
                        }
                    },
                    error: function (xhr, status, err) {
                        log_1.default.error('MessageManager::fetchIMRemoteReadTimeByTime fail xhr:' + xhr + ' status:' + status + ' err:' + err);
                        return reject({ code: constant_2.SDKRESCODE.UNKNOWN_ERROR, message: 'xhr:' + xhr + ' status:' + status + ' err:' + err });
                    }
                });
            });
        }
    };
    SessionManager.prototype.fetchPubRemoteReadTimeByTime = function (_a) {
        var _this = this;
        var _b = _a.startTime, startTime = _b === void 0 ? Date.now() - this._PubTimeRange : _b;
        if (this._PubTimeRange === 0) {
            log_1.default.log('SessionManager::fetchPubRemoteReadTimeByTime _PubTimeRange 0');
            return promise_1.default.resolve([{}, {}]);
        }
        else {
            return new promise_1.default(function (resolve, reject) {
                log_1.default.log('SessionManager::fetchPubRemoteReadTimeByTime startTime:' + startTime);
                _this.mtdx.HTTP.Pub.unreads({
                    data: {
                        ts: startTime,
                        type: 1,
                        od: 'desc'
                    },
                    success: function (result) {
                        if (0 !== result.rescode) {
                            log_1.default.log('SessionManager::fetchPubRemoteReadTimeByTime fail rescode:' + result.rescode);
                            return reject({ code: result.rescode, message: result });
                        }
                        else {
                            var syncData = result.data.sync_data ? _this._parsePubRead(result.data.sync_data) : {};
                            var syncData2 = result.data.sync_data2 ? _this._parsePubRead(result.data.sync_data2) : {};
                            log_1.default.log('SessionManager::fetchPubRemoteReadTimeByTime success rescode:' + result.rescode
                                + ' syncData:' + (syncData && syncData.readItems ? syncData.readItems.length : 0)
                                + ' syncData2:' + (syncData2 && syncData2.readItems ? syncData2.readItems.length : 0));
                            resolve([
                                syncData,
                                syncData2
                            ]);
                        }
                    },
                    error: function (xhr, status, err) {
                        log_1.default.error('MessageManager::fetchPubRemoteReadTimeByTime fail xhr:' + xhr + ' status:' + status + ' err:' + err);
                        return reject({ code: constant_2.SDKRESCODE.UNKNOWN_ERROR, message: 'xhr:' + xhr + ' status:' + status + ' err:' + err });
                    }
                });
            });
        }
    };
    SessionManager.prototype.mergeLocalAndRemoteReadItemDataAndUpdateServer = function (_a) {
        var existReadTime = _a.existReadTime, remoteReadItemData = _a.remoteReadItemData;
        log_1.default.log('SessionManager::mergeLocalAndRemoteReadItemDataAndUpdateServer');
        var readItemData = __assign({}, remoteReadItemData);
        var shouldUpdateIMReadTimes = [];
        var shouldUpdateIMReadTimes2 = [];
        var shouldUpdatePubReadTimes = [];
        var shouldUpdatePubReadTimes2 = [];
        for (var sessionId in existReadTime) {
            // 服务端没有本地会话已读时间,或者本地已读时间大于服务端已读时间
            if ((!readItemData[sessionId] && existReadTime[sessionId].svrTime > 0 && existReadTime[sessionId].svrTime > Date.now() - 3 * 24 * 60 * 60 * 1000) || (readItemData[sessionId] && existReadTime[sessionId].svrTime > readItemData[sessionId].svrTime)) {
                if (existReadTime[sessionId].sessionType === constant_1.SESSION_TYPE.CHAT || existReadTime[sessionId].sessionType === constant_1.SESSION_TYPE.GROUP_CHAT) {
                    shouldUpdateIMReadTimes.push(existReadTime[sessionId]);
                }
                if (existReadTime[sessionId].sessionType === constant_1.SESSION_TYPE.CHAT2) {
                    shouldUpdateIMReadTimes2.push(existReadTime[sessionId]);
                }
                if (existReadTime[sessionId].sessionType === constant_1.SESSION_TYPE.PUB_CHAT || existReadTime[sessionId].sessionType === constant_1.SESSION_TYPE.CS_CHAT) {
                    shouldUpdatePubReadTimes.push(existReadTime[sessionId]);
                }
                if (existReadTime[sessionId].sessionType === constant_1.SESSION_TYPE.PUB_CHAT2 || existReadTime[sessionId].sessionType === constant_1.SESSION_TYPE.CS_CHAT2) {
                    shouldUpdatePubReadTimes2.push(existReadTime[sessionId]);
                }
                log_1.default.log('SessionManager::mergeLocalAndRemoteReadItemDataAndUpdateServer 本地会话的已读时间大于服务端已读时间 sessionId:' + sessionId
                    + ' session svrTime:' + existReadTime[sessionId].svrTime + ' readItem svrTime:' + (readItemData[sessionId] ? readItemData[sessionId].svrTime : 0));
                readItemData[sessionId] = __assign(__assign({}, readItemData[sessionId]), { svrTime: existReadTime[sessionId].svrTime, time: existReadTime[sessionId].svrTime });
            }
        }
        this.sendRead({
            sessionType: constant_1.SESSION_TYPE.CHAT,
            readArray: shouldUpdateIMReadTimes.map(function (readItem) {
                var _a = sessionIdProcessor_1.default.parseSessionId(readItem.sessionId), uid = _a.uid, channelId = _a.channelId;
                return {
                    chatId: uid,
                    channelId: channelId,
                    sessionType: readItem.sessionType,
                    time: readItem.svrTime,
                    svrTime: readItem.svrTime,
                    peerAppId: userData_1.default.get('appId')
                };
            })
        });
        this.sendRead({
            sessionType: constant_1.SESSION_TYPE.CHAT2,
            readArray: shouldUpdateIMReadTimes2.map(function (readItem) {
                var _a = sessionIdProcessor_1.default.parseSessionId(readItem.sessionId), uid = _a.uid, channelId = _a.channelId, sid = _a.sid;
                return {
                    chatId: uid,
                    channelId: channelId,
                    sid: sid,
                    sessionType: readItem.sessionType,
                    time: readItem.svrTime,
                    svrTime: readItem.svrTime,
                    peerAppId: userData_1.default.get('appId')
                };
            })
        });
        this.sendRead({
            sessionType: constant_1.SESSION_TYPE.PUB_CHAT,
            readArray: shouldUpdatePubReadTimes.map(function (readItem) {
                var _a = sessionIdProcessor_1.default.parseSessionId(readItem.sessionId), uid = _a.uid, channelId = _a.channelId;
                return {
                    chatId: uid,
                    channelId: channelId,
                    sessionType: readItem.sessionType,
                    time: readItem.svrTime,
                    svrTime: readItem.svrTime,
                    peerAppId: userData_1.default.get('appId')
                };
            })
        });
        this.sendRead({
            sessionType: constant_1.SESSION_TYPE.PUB_CHAT2,
            readArray: shouldUpdatePubReadTimes2.map(function (readItem) {
                var _a = sessionIdProcessor_1.default.parseSessionId(readItem.sessionId), uid = _a.uid, channelId = _a.channelId, sid = _a.sid;
                return {
                    chatId: uid,
                    channelId: channelId,
                    sid: sid,
                    sessionType: readItem.sessionType,
                    time: readItem.svrTime,
                    svrTime: readItem.svrTime,
                    peerAppId: userData_1.default.get('appId')
                };
            })
        });
        return readItemData;
    };
    SessionManager.prototype.fetchHistoryMessagesAndCountUnread = function (_a) {
        var _b = _a.unreadSessions, unreadSessions = _b === void 0 ? [] : _b;
        log_1.default.log('SessionManager::fetchHistoryMessagesAndCountUnread begin unreadSessions size:' + (unreadSessions ? unreadSessions.length : 0));
        var IMSessions = [];
        var IMSessions2 = [];
        var PubSessions = [];
        var PubSessions2 = [];
        unreadSessions.forEach(function (session) {
            switch (session.type) {
                case constant_1.SESSION_TYPE.CHAT:
                case constant_1.SESSION_TYPE.CHAT2:
                case constant_1.SESSION_TYPE.GROUP_CHAT: {
                    if (session.svrTime > Date.now() - IM_EARLIEST_TIME_IN_HISTORY_RANGE) {
                        if (session.type === constant_1.SESSION_TYPE.CHAT2) {
                            IMSessions2.push(session);
                        }
                        else {
                            IMSessions.push(session);
                        }
                    }
                    else {
                        log_1.default.log('SessionManager::fetchHistoryMessagesAndCountUnread over max time session:' + session);
                    }
                    break;
                }
                case constant_1.SESSION_TYPE.PUB_CHAT:
                case constant_1.SESSION_TYPE.CS_CHAT:
                case constant_1.SESSION_TYPE.PUB_CHAT2:
                case constant_1.SESSION_TYPE.CS_CHAT2: {
                    if (session.svrTime > Date.now() - PUB_EARLIEST_TIME_IN_HISTORY_RANGE) {
                        if (session.type === constant_1.SESSION_TYPE.PUB_CHAT2 || session.type === constant_1.SESSION_TYPE.CS_CHAT2) {
                            PubSessions2.push(session);
                        }
                        else {
                            PubSessions.push(session);
                        }
                    }
                    else {
                        log_1.default.log('SessionManager::fetchHistoryMessagesAndCountUnread over max time session:' + session);
                    }
                    break;
                }
            }
        });
        log_1.default.log('SessionManager::fetchHistoryMessagesAndCountUnread end IMSessions:' + (IMSessions ? IMSessions.length : 0)
            + ' IMSessions2:' + (IMSessions2 ? IMSessions2.length : 0)
            + ' PubSessions:' + (PubSessions ? PubSessions.length : 0)
            + ' PubSessions2:' + (PubSessions2 ? PubSessions2.length : 0));
        return promise_1.default.all([
            this.fetchIMHistoryMessagesAndCountUnread({ sessions: IMSessions }),
            this.fetchPubHistoryMessagesAndCountUnread({ sessions: PubSessions }),
            this.fetchIMHistoryMessagesAndCountUnread({ sessions: IMSessions2 }, constant_1.SESSION_TYPE.CHAT2),
            this.fetchPubHistoryMessagesAndCountUnread({ sessions: PubSessions2 }, constant_1.SESSION_TYPE.PUB_CHAT2)
        ]);
    };
    SessionManager.prototype.fetchIMHistoryMessagesAndCountUnread = function (_a, sessionType) {
        var _this = this;
        var sessions = _a.sessions;
        if (sessionType === void 0) { sessionType = constant_1.SESSION_TYPE.CHAT; }
        return new promise_1.default(function (resolve, reject) {
            log_1.default.log('SessionManager::fetchIMHistoryMessagesAndCountUnread sessions size:' + (sessions ? sessions.length : 0));
            _this.fetchIMHistoryMessagesByCycleAndCountUnread({ sessions: sessions, resolve: resolve, reject: reject }, sessionType);
        });
    };
    SessionManager.prototype.fetchIMHistoryMessagesByCycleAndCountUnread = function (_a, sessionType) {
        var _this = this;
        var _b = _a.sessions, sessions = _b === void 0 ? [] : _b, resolve = _a.resolve, reject = _a.reject;
        if (sessionType === void 0) { sessionType = constant_1.SESSION_TYPE.CHAT; }
        var remainSessions = __spreadArrays(sessions);
        // 使用 splice 方法会改变 remainSessions,所以后续不需要再进行切分
        var currentSessions = remainSessions.splice(0, 10);
        log_1.default.log('SessionManager::fetchIMHistoryMessagesByCycleAndCountUnread sessions size:' + (currentSessions ? currentSessions.length : 0));
        if (currentSessions.length === 0) {
            resolve();
        }
        else {
            var sessionDataArray = currentSessions.map(function (session) {
                return __assign({ b: session.uid, ai: session.channelId <= 0 ? (session.appId <= 0 ? userData_1.default.get('appId') : session.appId) : userData_1.default.get('appId'), chid: session.channelId, 
                    // 为了后端查询效率,最多查询一个月内的历史消息用于补全未读数
                    st: session.readTime && session.readTime > Date.now() - IM_EARLIEST_TIME_IN_HISTORY_RANGE ? session.readTime : Date.now() - IM_EARLIEST_TIME_IN_HISTORY_RANGE, et: BIG_TIME, g: (session.isChat() || session.isChat2()) ? 0 : 1 }, (session.sid ? { sid: session.sid } : {}));
            });
            // 因为单聊和群聊拉取历史消息接口一样,因此 type 可以都用单聊
            message_manager_1.default.fetchMultiSessionsHistoryMessagesByTimeRange({ type: sessionType, limit: 100, sessionDataArray: sessionDataArray }).then(function () {
                log_1.default.log('SessionManager::fetchIMHistoryMessagesByCycleAndCountUnread result sessions size:' + (currentSessions ? currentSessions.length : 0));
                _this.countUnreadSessions({ sessions: currentSessions });
                _this.fetchIMHistoryMessagesByCycleAndCountUnread({ sessions: remainSessions, resolve: resolve, reject: reject }, sessionType);
            }).catch(function (e) {
                log_1.default.error('SessionManager::fetchIMHistoryMessagesByCycleAndCountUnread error:', e);
                _this.fetchIMHistoryMessagesByCycleAndCountUnread({ sessions: remainSessions, resolve: resolve, reject: reject }, sessionType);
            });
        }
    };
    SessionManager.prototype.fetchPubHistoryMessagesAndCountUnread = function (_a, sessionType) {
        var _this = this;
        var sessions = _a.sessions;
        if (sessionType === void 0) { sessionType = constant_1.SESSION_TYPE.PUB_CHAT; }
        return new promise_1.default(function (resolve, reject) {
            log_1.default.log('SessionManager::fetchPubHistoryMessagesAndCountUnread sessions size:' + (sessions ? sessions.length : 0));
            _this.fetchPubHistoryMessagesByCycleAndCountUnread({ sessions: sessions, resolve: resolve, reject: reject }, sessionType);
        });
    };
    SessionManager.prototype.fetchPubHistoryMessagesByCycleAndCountUnread = function (_a, sessionType) {
        var _this = this;
        var _b = _a.sessions, sessions = _b === void 0 ? [] : _b, resolve = _a.resolve, reject = _a.reject;
        if (sessionType === void 0) { sessionType = constant_1.SESSION_TYPE.PUB_CHAT; }
        var remainSessions = __spreadArrays(sessions);
        // 使用 splice 方法会改变 remainSessions,所以后续不需要再进行切分
        var currentSessions = remainSessions.splice(0, 10);
        log_1.default.log('SessionManager::fetchPubHistoryMessagesByCycleAndCountUnread sessions:' + message_util_1.default.getSessionArrayPrint(currentSessions));
        if (currentSessions.length === 0) {
            resolve();
        }
        else {
            var sessionDataArray = currentSessions.map(function (session) {
                return __assign({ u: session.pubId, pu: session.peerUid, st: session.readTime && session.readTime > Date.now() - PUB_EARLIEST_TIME_IN_HISTORY_RANGE ? session.readTime : Date.now() - PUB_EARLIEST_TIME_IN_HISTORY_RANGE, et: BIG_TIME }, (session.sid ? { sid: session.sid } : {}));
            });
            message_manager_1.default.fetchMultiSessionsHistoryMessagesByTimeRange({ type: sessionType, limit: 100, sessionDataArray: sessionDataArray }).then(function () {
                _this.countUnreadSessions({ sessions: currentSessions });
                _this.fetchPubHistoryMessagesByCycleAndCountUnread({ sessions: remainSessions, resolve: resolve, reject: reject }, sessionType);
            }).catch(function (e) {
                log_1.default.error('fetchPubHistoryMessagesByCycle', e);
                _this.fetchPubHistoryMessagesByCycleAndCountUnread({ sessions: remainSessions, resolve: resolve, reject: reject }, sessionType);
            });
        }
    };
    SessionManager.prototype.countUnreadSessions = function (_a) {
        var _this = this;
        var sessions = _a.sessions;
        log_1.default.log('SessionManager::countUnreadSessions begin sessions:' + sessions);
        var updatedSessions = sessions.map(function (session) {
            session.unreads = _this.countUnreadByMessages({ session: session });
            session.setCountUnreadFlag(true);
            return session;
        });
        log_1.default.log('SessionManager::countUnreadSessions end sessions:' + sessions);
        this.saveSessions(updatedSessions);
    };
    SessionManager.prototype.countUnreadByMessages = function (_a) {
        var _this = this;
        var session = _a.session;
        var _b = sessionIdProcessor_1.default.parseSessionId(session.sessionId), uid = _b.uid, channelId = _b.channelId, sid = _b.sid;
        var messages = message_manager_1.default.getMessages(uid, channelId, sid);
        var unreads = messages.reduce(function (unread, message) {
            if (_this.isShouldCountUnread(session, message)) {
                return unread + 1;
            }
            return unread;
        }, 0);
        return unreads;
    };
    SessionManager.prototype.fetchIMRemoteSessionListByTimeByOrder = function (_a) {
        var _b = _a.day, day = _b === void 0 ? 5 : _b;
        var lastIMSession = this.getSortedSessionList().reverse().find(function (session) {
            if (session.isChat() || session.isChat2() || session.isGroupChat()) {
                return true;
            }
        });
        var endTime = lastIMSession && lastIMSession.svrTime ? lastIMSession.svrTime : void 0;
        var startTime = this._lastFetchIMSessionListTime - day * 24 * 60 * 60 * 1000;
        log_1.default.log('SessionManager::fetchIMRemoteSessionListByTimeByOrder day:' + day
            + ' startTime:' + startTime + ' endTime:' + endTime);
        return this.fetchIMRemoteSessionListByTime({ startTime: startTime, endTime: endTime });
    };
    SessionManager.prototype.fetchPubRemoteSessionListByTimeByOrder = function (_a) {
        var _b = _a.day, day = _b === void 0 ? 5 : _b;
        var lastPubSession = this.getSortedSessionList().reverse().find(function (session) {
            if (session.isPubChat() || session.isPubChat2() || session.isCSChat()) {
                return true;
            }
        });
        var endTime = lastPubSession && lastPubSession.svrTime ? lastPubSession.svrTime : void 0;
        var startTime = this._lastFetchPubSessionListTime - day * 24 * 60 * 60 * 1000;
        log_1.default.log('SessionManager::fetchPubRemoteSessionListByTimeByOrder day:' + day
            + ' startTime:' + startTime + ' endTime:' + endTime);
        return this.fetchPubRemoteSessionListByTime({ startTime: startTime, endTime: endTime });
    };
    SessionManager.prototype.getTotalUnreadNumber = function () {
        return this._sessionMap.values().reduce(function (prev, session) {
            return prev + session.unreads;
        }, 0);
    };
    SessionManager.prototype.dealReceiveDataMessage = function (dataMessages) {
        var _this = this;
        try {
            if (!dataMessages) {
                return;
            }
            dataMessages.forEach(function (dataMessageObject) {
                if (!dataMessageObject) {
                    return;
                }
                if (dataMessageObject.type == 152) { // 删除会话
                    var jsonObject = JSON.parse(dataMessageObject.data);
                    var action = jsonObject['action'] || '';
                    if (action === 'imExt' || action === 'pubExt') {
                        _this.onReceiveSessionExtInfo(jsonObject['chat']);
                    }
                    else if (_this._isLoginSuccessSessionListGetFinish) {
                        log_1.default.info('SessionManager::dealReceiveDataMessage delete session message:' + dataMessageObject);
                        if (action === 'pubChatAll' || action === 'imChatAll') {
                            var channels_1 = jsonObject['channels'];
                            if (channels_1 && channels_1.length > 0) {
                                var cleanTs_1 = jsonObject['cleanTs'] || 0;
                                var memorySessions_1 = _this.getSortedSessionList() || [];
                                _this.getSessionFromDB().then(function (sessions) {
                                    // 此处不用根据会话类型删除会话，因为需求是删除小于某个时间某个channel的会话，由于服务端实现区分了im和pub，所以会分别发送透传指令。。。
                                    var targetSessions = sessions && sessions.length > memorySessions_1.length ? sessions : memorySessions_1;
                                    _this.deleteLocalSessionsByCondition(targetSessions, channels_1, [], cleanTs_1, true);
                                }).catch(function (e) {
                                    log_1.default.error('SessionManager::dealReceiveDataMessage error:' + e);
                                });
                            }
                            else {
                                log_1.default.error('SessionManager::dealReceiveDataMessage delete session not found channels');
                            }
                        }
                        else if (action === 'imchat' || action === 'pubchat') {
                            var chats = jsonObject['chat'];
                            var deletedSessions_1 = [];
                            if (chats && chats.length > 0) {
                                chats.forEach(function (element) {
                                    var u = element['u'] || element['b'] || '';
                                    var pu = element['pu'] || '';
                                    var chid = element['chid'] || 0;
                                    var sid = element['sid'] || '';
                                    var uid = pu === '' ? u : u + '_' + pu;
                                    var deleteSession = _this.getSession(uid, chid, sid);
                                    if (deleteSession) {
                                        deletedSessions_1.push(deleteSession);
                                    }
                                });
                                if (deletedSessions_1 && deletedSessions_1.length > 0) {
                                    _this.deleteLocalSessions(deletedSessions_1, true);
                                }
                            }
                        }
                    }
                    else {
                        if (_this._deleteSessionDataMessageCache) {
                            _this._deleteSessionDataMessageCache.push(dataMessageObject);
                        }
                        else {
                            _this._deleteSessionDataMessageCache = [];
                            _this._deleteSessionDataMessageCache.push(dataMessageObject);
                        }
                    }
                }
            });
        }
        catch (error) {
            log_1.default.error('dealReceiveDataMessage error info:' + error);
        }
        return false;
    };
    SessionManager.prototype.fetchIMSessionListExtInfo = function (_a) {
        var _this = this;
        var startTime = _a.startTime, endTime = _a.endTime;
        return new promise_1.default(function (resolve, reject) {
            message_manager_1.default.fetchSessionListInfoCycle({ svid: constant_3.SVID.SVID_IM, prev: new Array(), startTime: startTime, endTime: endTime, fields: ['ext'], resolve: resolve, reject: reject });
        }).then(function (infoArray) {
            try {
                return { msgs: _this.parseSessionExtInfo(infoArray) };
            }
            catch (error) {
                log_1.default.error('MessageManager::fetchIMSessionListExtInfo parse error:' + error);
                return promise_1.default.reject(error);
            }
        }).catch(function (error) {
            log_1.default.error('MessageManager::fetchIMSessionListExtInfo error:' + error);
            return promise_1.default.reject(error);
        });
    };
    SessionManager.prototype.fetchPubSessionListExtInfo = function (_a) {
        var _this = this;
        var startTime = _a.startTime, endTime = _a.endTime;
        return new promise_1.default(function (resolve, reject) {
            message_manager_1.default.fetchSessionListInfoCycle({ svid: constant_3.SVID.SVID_PUB, prev: new Array(), startTime: startTime, endTime: endTime, fields: ['ext'], resolve: resolve, reject: reject });
        }).then(function (infoArray) {
            try {
                return { msgs: _this.parseSessionExtInfo(infoArray) };
            }
            catch (error) {
                log_1.default.error('MessageManager::fetchPubSessionListExtInfo parse error:' + error);
                return promise_1.default.reject(error);
            }
        }).catch(function (error) {
            log_1.default.error('MessageManager::fetchPubSessionListExtInfo error:' + error);
            return promise_1.default.reject(error);
        });
    };
    SessionManager.prototype.parseSessionIdByHttpProto = function (item) {
        var obj = {
            type: '',
            uid: '0',
            channelId: item.chid,
            sid: item.sid || '',
        };
        if (item.u) {
            if (item.pu && (item.pu != 0 || item.pu != '')) {
                obj.uid = item.u + '_' + item.pu;
                if (item.sid && (item.sid != '' || item.sid != '0')) {
                    obj.type = constant_1.SESSION_TYPE.CS_CHAT2;
                }
                else {
                    obj.type = constant_1.SESSION_TYPE.CS_CHAT;
                }
            }
            else {
                obj.uid = item.u + '';
                if (item.sid && (item.sid != '' || item.sid != '0')) {
                    obj.type = constant_1.SESSION_TYPE.PUB_CHAT2;
                }
                else {
                    obj.type = constant_1.SESSION_TYPE.PUB_CHAT;
                }
            }
        }
        else {
            obj.uid = item.b + '';
            if (item.g && item.g == 1) {
                obj.type = constant_1.SESSION_TYPE.GROUP_CHAT;
            }
            else {
                if (item.sid && (item.sid != '' || item.sid != '0')) {
                    obj.type = constant_1.SESSION_TYPE.CHAT2;
                }
                else {
                    obj.type = constant_1.SESSION_TYPE.CHAT;
                }
            }
        }
        return obj;
    };
    SessionManager.prototype.parseSessionExtInfo = function (protoInfoArray) {
        var _this = this;
        var ret = [];
        protoInfoArray.forEach(function (item) {
            var obj = _this.parseSessionIdByHttpProto(item);
            obj['ext'] = item.ext;
            obj['extTs'] = item.extTs;
            ret.push(obj);
        });
        return ret;
    };
    SessionManager.prototype.onReceiveSessionExtInfo = function (protoInfoArray) {
        event_emitter_1.default.emit(event_emitter_1.EVENT_NAME.RECEIVE_SESSION_EXT_INFO, { messages: this.parseSessionExtInfo(protoInfoArray) });
    };
    return SessionManager;
}());
exports.default = new SessionManager();


//# sourceURL=webpack://MTDX/./src/extra/managers/session-manager.ts?